# Create your views here.
from django import newforms as forms
from django.shortcuts import render_to_response, get_object_or_404
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse
from django.template import RequestContext

from wjContact.contacts.models import Contacts
# ...

## Make various forms which will use in our views

ContactForm = forms.form_for_model(Contacts)
#ComputerForm = forms.form_for_model(Computer)
#SalesForm = forms.form_for_model(Sales)
## May  end up just using the  "AdminInterface" for adding new Computer Classes or
## Computer components.Anyway, don't bother building forms for them just yet!
#ComputerClassForm = forms.form_for_model(Computer_class)
#ComputerComponentsForm = forms.form_for_model(Computer_components)

## The following "logout" method is copied from the django.contrib.admin module.
## Could also just call the one thereprobably in th long run, but in the
## interests of figuring out what is going on I have copied it here. 
##
## Ultimately we probably want the logout views at the level of the entire
## website (wjContact) rather than down here in the contacts app, so look into
## that at some point.
def logout(request, next_page=None, template_name='registration/logged_out.html'):
    "Logs out the user and displays 'You are logged out' message."
    from django.contrib.auth import logout
    logout(request)
    if next_page is None:
        #return render_to_response(template_name)
        return render_to_response(template_name, {'title': _('Logged out')}, context_instance=RequestContext(request))
    else:
        # Redirect to this page until the session has been cleared.
        #HttpResponseRedirect
        #    The constructor takes a single argument the path to redirect to. This 
        #    can be a fully qualified URL (e.g. 'http://www.yahoo.com/search/') or 
        #    an absolute URL with no domain (e.g. '/search/'). Note that this returns 
        #    an HTTP status code 302.   
        return HttpResponseRedirect(next_page or request.path)
    


    
from django.contrib.auth.decorators import login_required
from django.contrib.admin.views.decorators import staff_member_required
from django.views.decorators.cache import never_cache
from django.contrib.auth.views import redirect_to_login

###@never_cache

#===================================== 

def editContacts(request):
    ## do stuff
    #edit_form
    """# Create an Author.
>>> a = Author(name='Joe Smith', title='MR', birth_date=None)
>>> a.save()

# Create a form for this particular Author.
>>> AuthorForm = form_for_instance(a)

# Instantiate the form.
>>> f = AuthorForm() """
    if request.method == 'POST':
        edit_form = ContactForm(request.POST)  
        edit_form.fields['state'].max_length = 2
        if edit_form.is_valid():
            # Do form processing here...    
            #edit_from.auto_id =
            #new = edit_form._model.objects.get(pk=2) 
            import pdb
            pdb.set_trace()                     
            new.save()
   
            # Always return an HttpResponseRedirect after successfully dealing
            # with POST data. This prevents data from being posted twice if a
            # user hits the Back button.
            return HttpResponseRedirect(reverse('wjContact.contacts.views.indexContacts'))
        else:
            return render_to_response('edit.html', {'edit_form': edit_form, 
                                           })     
    else:  
        ## Display the details for the contact we are editing.
        contact = Contacts.objects.get(pk=2)
        EditContactForm = forms.form_for_instance(contact)
        edit_form = EditContactForm()
        return render_to_response('edit.html', {'edit_form': edit_form, 
                                           })
editContacts = login_required(editContacts)

####################################


#@login_required
def addContacts(request):
    """ """
    if request.method == 'POST':
        wendyform = ContactForm(request.POST)
        wendyform.fields['state'].max_length = 2
        if wendyform.is_valid():
            # Do form processing here...
            ## Here we will check for rough matches existing in database 
            ## already.
            fname = wendyform.clean()['first_name']
            dupes = Contacts.objects.filter(first_name__icontains=fname)
            if dupes:
                ## List possible duplicates
                return render_to_response('dupes.html', {'dupelist': dupes})                                
            else:
                wendyform.save()
                # Always return an HttpResponseRedirect after successfully dealing
                # with POST data. This prevents data from being posted twice if a
                # user hits the Back button.
                return HttpResponseRedirect(reverse('wjContact.contacts.views.indexContacts'))
        else:
            return render_to_response('add.html', {'wendyform': wendyform, 
                                           })
            
    else:
            wendyform = ContactForm()
            ## Need to change the name of the index.html template to "addForm" or similar.
            return render_to_response('add.html', {'wendyform': wendyform, 
                                           })
addContacts = login_required(addContacts)

def detailsContacts(request, contact_id):
    """ Show the details for a specific contact"""
    details = get_object_or_404(Contacts, pk=contact_id)
    details_dict = {'first_name': details.first_name, 
               'homephone': details.homephone,
               'database id' : details.id,
               'a string': 'a string',
    }
    return render_to_response('details.html', {'details': details_dict})

def indexContacts(request):
    """ List all contacts."""
    names = Contacts.objects.values('first_name','last_name').order_by('last_name')
    return render_to_response('index.html', {'contact_list': names})



def searchContacts(request):
    ## 1. display a search form - built from the Contacts model. This is just
    ## an "unbound" ContactForm.
    search_form = ContactForm()
    ## 2. Get user input from the form - these are the fields they want us to 
    ## search. Currently limited to first_name.
    ## 3. Search the database 
    ## 4. List results (use the existing index.html template
    if request.method == 'GET':
        search_form = ContactForm(request.GET)
        search_form.fields['state'].max_length = 2
        for field in search_form.fields.values():
            ## For searching, not all fields are required.
            field.required = False         
        if search_form.is_valid():
            # Do form processing here...
            ## Here we will check for rough matches existing in database 
            ## already.
            fname = search_form.clean()['first_name']
            results = Contacts.objects.filter(first_name__icontains=fname)
            ## List results
            return render_to_response('index.html', {'contact_list': results})                                

        else:
            return render_to_response('search.html', {'search_form': search_form, 
                                           })        
    else:
            searchform = ContactForm()
            ## Need to change the name of the index.html template to "addForm" or similar.
            return render_to_response('search.html', {'search_form': search_form, 
                                           })
searchContacts = login_required(searchContacts)
    
    
##############################################################
## Computers
##############################################################
@login_required
def addComputerForm(request):
    if request.method == 'POST':
        comp_form = ContactForm(request.POST)
        if comp_form.is_valid():
            # Do form processing here...
            comp_form.save()
            # Always return an HttpResponseRedirect after successfully dealing
            # with POST data. This prevents data from being posted twice if a
            # user hits the Back button.
        return HttpResponseRedirect(reverse('wjContact.contacts.views.indexComputers'))
    else:
        comp_form = ContactForm()
    ## Need to change the name of the index.html template to "addForm" or similar.
    dummy = "dummy"
    return render_to_response('add.html', {'form': comp_form, 
                                           })

def detailsComputers(request, comp_id):
    """ Show the details for a specific computer"""
    details = get_object_or_404(Computers, pk=comp_id)
    details_dict = {'first_name': details.first_name, 
               'homephone': details.homephone,
               'database id' : details.id,
               'a string': 'a string',
    }
    return render_to_response('details.html', {'details': details_dict})

def indexComputers(request):
    """ List all computers."""
    computers = Computers.objects.values('first_name','last_name').order_by('last_name')
    return render_to_response('index.html', {'contact_list': names})
##############################################################
##############################################################
##############################################################

#class ContactForm(forms.Form):
    #first_name = forms.CharField(maxlength=20)
    #last_name = forms.CharField(maxlength=20)
    #address = forms.CharField(maxlength=200)
    #suburb = forms.CharField(maxlength=40)
    #country = forms.CharField(maxlength=40)
    #homephone = forms.CharField(maxlength=40)
    #workphone = forms.CharField(maxlength=40)
    #mobile = forms.CharField(maxlength=20)
    #email = forms.EmailField() # database field has maxlength = 60
    
#        return render_to_response('add.html', {'wendyform': wendyform, 
#                                           'mycwd': mycwd,
#                                           'settings_media_root': settings_media_root,
#                                           'settings_media_url': settings_media_url,
#                                           'css_files': css_files,
#                                           'settings': settings,
#                                           'username': request.user.username,
#                                           'is_authenticated' : request.user.is_authenticated(),
#                                           })
